package com.jiang.entity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class PeerReader extends Thread{
    private static final Logger LOGGER = LoggerFactory.getLogger(PeerReader.class);
    private Socket socket;

    //设置缓冲区
    private ArrayList<String> receiveData = new ArrayList<String>();
    public PeerReader(Socket socket) {
        this.socket = socket;//传入的是客户端的套接字
    }


    @Override
    public void run() {
        //读的线程就有自己的作用，读
        try{
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//通过这个套接字读取客户端输入数据
            String input;
            while((input = in.readLine()) != null){
                receiveData.add(input);
            }

        } catch (Exception e) {
            LOGGER.info("Peer"+socket.getInetAddress()+"disconnected.", e);
        }
    }

    /**
     * 取出缓冲数据
     * @return
     */
    public List<String> readData(){
        ArrayList<String> inputBuffer = new ArrayList<String>(receiveData);
        receiveData.clear();//清除缓冲区里的数据
        return inputBuffer;
    }
}
